<?php
namespace Admin\Controller;
use Think\Controller;
class WarehouseController extends BaseController {
	public function _initialize()
    {
        parent::_initialize();
		//数据库连接基础配置-begin
		C('db_config.DB_TYPE',C('DB_TYPE'));
		C('db_config.DB_HOST',C('DB_HOST'));
		C('db_config.DB_USER',C('DB_USER'));
		C('db_config.DB_PWD',C('DB_PWD'));
		C('db_config.DB_PORT',C('DB_PORT'));
		C('db_config.DB_CHARSET',C('DB_CHARSET'));
		//数据库连接基础配置-end
    }
	public function examined(){
		$ids=I('ids');
		$map['id']=array('in',$ids);
		$val=I('val');
		$data['status']=$val;
		$res=M('Warehouse')->where($map)->save($data);
		// echo M('Warehouse')->getlastsql();
		if($res!==false){
			alert(1,'成功');
		}else{
			alert(0,'失败');
		}
	}
    public function index(){
        $name=I("name");
        if(!empty($name)){
            $where['company']=array('like',"%$name%");
        }

        $warehouse = M('warehouse');

		$department = M('DepartmentWarehouse');
        $count      = $warehouse->where($where)->count();
        $Page       = new \Think\Page($count,15);
        $show       = $Page->show();
		// dump($count);
        $list = $warehouse->where($where)->limit($Page->firstRow.','.$Page->listRows)->order("id desc")->group("warehouse_code")->select();
		// echo $warehouse->getlastsql();
		foreach($list as $k=>$v){
			$department_name=$department->where(array('id'=>$v['department_id']))->find();

			$list[$k]['department_name']=$department_name['name'];
			$list[$k]['company_name']=$member_info['company'];
			$list[$k]['feerule_name']=$feerule_info['name'];
		}
		$department_list=$department->select();
		
		$this->assign('department_list',$department_list);
        $this->assign('list',$list);
        $this->assign('page',$show);
        $this->assign('count',$count);
        $this->display();
    }
	//绑定角色
	public function bind_role_warehouse(){
		$m=M('DepartmentWarehouse');
		$list=$m->select();
		$this->assign('list',$list);
		$this->display();
	}
	
	//同步角色权限
	public function pushDepartment($db_name,$d_id){
		$m=M('DepartmentWarehouse');
		$n=M('RootWarehouse');
		$r=M('AuthRule', C('DB_PREFIX_TT'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . $db_name);
		$m_info=$m->find($d_id);
		$root_group_id=explode(',',$m_info['root_group_id']);
		$map['id']=array('in',$root_group_id);
		$root_list=$n->where($map)->select();
		foreach($root_list as $k=>$v){
			$dataList[$k]['name'] = 'Admin/'.$v['controller'].'/'.$v['action'];
			$dataList[$k]['title'] = $v['name'];
			$dataList[$k]['id'] = $v['id'];
			$dataList[$k]['type'] = 1;
			$dataList[$k]['status'] = 1;
			$dataList[$k]['pid'] = $v['pid'];
			$dataList[$k]['o'] = $v['sort'];
			$dataList[$k]['icon'] = $v['icon'];
			$dataList[$k]['contr'] = $v['controller'];
			$dataList[$k]['func'] = $v['action'];
		}
		$sql = 'truncate table '.$db_name.'.'.C('DB_PREFIX_TT').'auth_rule';
		$stat=M()->execute($sql);//清空表
		$res=$r->addAll($dataList);
		return $res;
	}
	
	//同步角色
	public function confirm_bind_role_warehouse(){
		$m=M('Warehouse');
		$ids=I('ids');
		$ids=explode(',',$ids);

		$role_id=I('role_id');
		
		foreach($ids as $k=>$v){
			$data['department_id']=$role_id;
			$res=$m->where(array('id'=>$v))->save($data);
			if($res===false){
				$this->error('更新出错');
			}else{
				//同步角色
				$warehouse_info=$m->find($v);
				$result=$this->pushDepartment($warehouse_info['db_name'],$role_id);//同步角色
				
				if(!$result){
					$this->error('同步角色权限出错');
				}
				continue;
			}
		}
		$this->success('更新成功');
	}
	//同步角色
	public function confirm_bind_role_warehouse_s($ids,$role_id){
		$m=M('Warehouse');
		$ids=explode(',',$ids);
		foreach($ids as $k=>$v){
			$data['department_id']=$role_id;
			$res=$m->where(array('id'=>$v))->save($data);
			if($res===false){
				return 0;//更新出错
			}else{
				//同步角色
				$warehouse_info=$m->find($v);
				$result=$this->pushDepartment($warehouse_info['db_name'],$role_id);//同步角色
				
				if(!$result){
					return -1;//同步角色权限出错
				}
				continue;
			}
		}
		return 1;//更新成功
	}
	//api=1为接口调用
    public function addD($warehouse_name,$warehouse_code,$username,$nick_name,$pwd,$warehouse_cate,$api=0){
        if($warehouse_name==''){
            alert(0,'仓库名称不能为空');
        }
        if($warehouse_code==''){
            alert(0,'仓库编码不能为空');
        }
		if($username==''){
            alert(0,'手机号不能为空');
        }
		if(!mobile($username)){
            alert(0,'手机号错误');
        }
		if($pwd==''){
            alert(0,'密码不能为空');
        }
		if($warehouse_cate==''){
            alert(0,'请选择仓库类型');
        }
		$map['name']=$warehouse_name;
        $map['warehouse_code']=$warehouse_code;
		$map['username']=$username;
		$map['nick_name']=$nick_name;
		$map['_logic'] = 'or';
		
        $data['name']=$warehouse_name;
        $data['warehouse_code']=$warehouse_code;
		$data['username']=$username;
		$data['nick_name']=$nick_name;
		$data['password']=substr(md5($pwd),0,28);
		$data['warehouse_cate']=$warehouse_cate;
        $data['_logic'] = 'or';
        if(M("warehouse")->where($map)->count()>0){
			if($api){
				return 0;
			}else{
				alert(0,'手机号或仓库名称或者仓库编码或昵称已经存在');
			}
        }
        unset($data['_logic']);
		$dbName="tzwms_".$data['username'];//数据库名称 "tzwms_+手机号"		
		$data['db_name']=$dbName;
        $result= M("warehouse")->add($data);
        if($result){
			$this->createDb($username);//创建数据库
			$this->confirm_bind_role_warehouse_s($result,$warehouse_cate);//同步对应仓库角色权限
			if($api){
				return 1;
			}else{
				alert(1,'添加成功');
			}
        }else{
			if($api){
				return 0;
			}else{
				alert(0,'添加失败');
			}
        }
    }
	//创建数据库
	public function createDb($username){
		$data['username']=$username;
		//创建数据库 事务会自动提交
		$dbName="tzwms_".$data['username'];//数据库名称 "tzwms_+手机号"		
		$Model = M();
		$sql_head="SELECT * FROM information_schema.SCHEMATA where SCHEMA_NAME='$dbName';";
		$ress = $Model->query($sql_head);
		if(!empty($ress)){
			alert(0,'数据库已存在');
		}
		$res2 = $Model->execute('create database ' . $dbName);
		// dump(123);
		// die;
		if($res2 === false){
			alert(0,'生成数据失败！');
		}else{
			//使用读取写入方式导入
			require_once('./cloudAPP/Admin/Common/DBManage.class.php');
			$db = new \DBManage(C('DB_HOST'), C('DB_USER'), C('DB_PWD'), $dbName , 'utf8' );
			
			//输出缓存
			ob_start();
			//导入
			$db->restore('./data/hcf.sql');
			/*
			 * 同步企业用户数据库中用户信息与用户数据库中管理员信息
			 * 兼容原有数据表设计 不影响视图中的信息查询
			 */
			$connstr = C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . $dbName;
			$AuthUser = M('AuthUser','tz_',$connstr);
			$AuthGroupAccess = M('AuthGroupAccess','tz_',$connstr);
			$AuthGroup = M('AuthGroup','tz_',$connstr);
			$uid=$AuthUser->add(array('username' => $data['username'], 'password' => $data['password']));
			$AuthUser->where(array('username'=>$data['username']))->setField('uid',1);//更新注册账号的uid,默认为超级管理员
			
			$AuthGroup_data['id']=1;
			$AuthGroup_data['title']='超级管理员';
			$AuthGroup_data['status']=1;
			$AuthGroup_data['describe']='拥有最大权限';
			$AuthGroup->add($AuthGroup_data);//添加超级管理员角色

			$AuthGroupAccess->add(array('uid'=>1,'group_id'=>1));
			//清空缓冲
			ob_end_clean();
		}
	}
    public function editD($id,$name){
        if($name==''){
            alert(0,'单位名称不能为空');
        }
        if($id==''){
            alert(0,'操作有误');
        }
        $data['name']=trim($name);
        $data['operator']=session('admin');
        $result= M("warehouse")->where("id='".$id."'")->save($data);
        if($result){
            alert(1,'修改成功');
        }else{
            alert(0,'修改失败');
        }
    }
    public function del($id){
        if($id==''){
            alert(0,'操作有误');
        }
		$group_id=explode('@',$id);
        $i=0;
		foreach($group_id as $id){
            $db_name=M("warehouse")->where("id='".$id."'")->getField('db_name');
            $true=M()->execute("drop database if exists ".$db_name);
            $result= M("warehouse")->delete(ltrim($id,','));
            $i+=$result*1;
        }
        if(count($group_id)==$i){
            alert(1,'全部删除成功');
        }elseif($i>0){
            alert(1,'删除'.$i."个/共".count($group_id)."个");
        }else{
            alert(0,'删除失败');
        }
    }

    public function config($id){
        if(I("get.name")!==null && I("get.name")!==''){
            $where['name']=array('like','%'.I("get.name").'%');
        }else{
            $where="1=1";
        }
        if($id==''){
            alert(0,'操作有误');
        }
		$warehouse=M('Warehouse');
		$db_name=$warehouse->where(array('id'=>$id))->getField('db_name');

		C('db_config.DB_NAME',$db_name);
		$c=M('config',C('DB_PREFIX_TT'),C('db_config'));

        $config = M('config');
        $count      = $config->where($where)->where("cate=2")->count();
        $Page       = new \Think\Page($count,15);
        $show       = $Page->show();
        $list = $config->where($where)->where("cate=2")->limit($Page->firstRow.','.$Page->listRows)->order("id desc")->select();
		foreach($list as $k=>$v){
			$list[$k]['value']=$c->where(array('en_name'=>$v['en_name']))->getField('value');
		}
        $this->assign('list',$list);
        $this->assign('page',$show);
        $this->assign('id',$id);
        $this->assign('count',$count);
        $this->display();
    }

    public function configEditD($warehouse_id,$name,$en_name,$value){
        if($name==''){
            alert(0,'变量名称不能为空');
        }
        if($en_name==''){
            alert(0,'英文名称不能为空');
        }
        if($value==''){
            alert(0,'值不能为空');
        }
		$w=M('warehouse');
		$db_name=$w->where(array('id'=>$warehouse_id))->getField('db_name');
		
		$map=array();
		$map['en_name']=$en_name;
		
		$data=array();
		$data['name']=$name;
		$data['en_name']=$en_name;
		$data['value']=$value;

		C('db_config.DB_NAME',$db_name);
		$c=M('Config',C('DB_PREFIX_TT'), C('db_config'));

		if($c->where($map)->count()){	//存在则修改值
			$result=$c->where($map)->save($data);
			if($result!==false){
				alert(1,'修改成功');
			}else{
				alert(0,'修改失败');
			}
		}else{	//新增值
			$result=$c->add($data);
			if($result){
				alert(1,'修改成功');
			}else{
				alert(0,'修改失败');
			}
		}
    }
	//升级数据库
	public function updateAll(){
		$m=M('Warehouse');
		$list=$m->where(array('warehouse_code'=>array('neq','41494474')))->order('id asc')->select();
		// echo $m->getlastsql();
		// die;
		require_once('./cloudAPP/Admin/Common/DBManage.class.php');
		foreach($list as $k=>$v){
			$dbname=$v['db_name'];//数据库名称
			echo "<div style='font-size:12px;'><br>当前操作仓库：".$v['name']."<br><br><br>";
			//使用读取写入方式导入
			$db = new \DBManage(C('DB_HOST'),C('DB_USER'),C('DB_PWD'),$dbname,'utf8');
			//导入
			$db->restore('./data/uw.sql');
			unset($db);
		}
		@unlink('./data/update.sql');//删除文件
    }
	//清空数据库
	public function truncateAll(){
		$m=M('Warehouse');
		$id=I('id');
		$warehouse_info=$m->where(array('id'=>$id))->find();
		require_once('./cloudAPP/Admin/Common/DBManage.class.php');
		$dbname=$warehouse_info['db_name'];//数据库名称
		echo "<div style='font-size:12px;'><br>当前操作仓库：".$warehouse_info['name']."<br><br><br>";
		//使用读取写入方式导入
		$db = new \DBManage(C('DB_HOST'),C('DB_USER'),C('DB_PWD'),$dbname,'utf8');
		//导入
		$db->restore('./data/truncate_warehouse.sql');
		unset($db);
    }
	//角色列表
    public function department(){
        $f=C('DB_PREFIX');
        $list = M('DepartmentWarehouse')->order('created_at desc')->select();
        $this->assign('list',$list);
        $this->display();
    }
	public function department_add(){
		$root=M('RootWarehouse')->order("sort")->select();
        $new_arr=array();
		foreach($root as $k=>$v){
            if($v['pid']==0){//顶级菜单
                foreach($root as $j=>$u){
					if($v['id']==$u['pid']){
						foreach($root as $js=>$us){
							if($u['id']==$us['pid']){
								foreach($root as $jss=>$uss){
									if($us['id']==$uss['pid']){
											$us['child'][]=$uss;
									}
								}
								$u['child'][]=$us;
							}
						}
						$v['child'][]=$u;
					}
				}
				$new_arr[]=$v;
            }
        }
		// dump($new_arr);
		// die;
		$this->assign('list',$new_arr);
        $this->display();
    }
	public function edit(){
		
		$id=I('id');
		$m=M('Warehouse');
		$department=M('DepartmentWarehouse');
		$list=$m->find($id);
		// dump($list);
		$department_list=$department->select();
		
		$this->assign('department_list',$department_list);
		$this->assign('list',$list);
		$this->display();
	}
	public function department_addD($name,$group_id){
        $this->p = M('RootWarehouse');
        if($name==''){
            alert(0,'部门名称为空');
        }
        if($group_id==''){
            alert(0,'权限不能为空');
        }
        $count=$this->p->where("name='".$name."'")->count();
        if($count>0){
            alert(0,'名称已经存在');
        }
        //////权限检查，是否具备这些权限
        $arr_id=explode(',',$group_id);
        foreach($arr_id as $v){
            if(!is_numeric($v)){
                alert('操作有误');
            }
        }
        $where['id']=array('IN',$arr_id);
        $result=$this->p->where($where)->getField('name',true);
        if(count($result)!=count($arr_id)){
            alert('操作有误');
        }
        $data['name']=$name;
        $massage=session('admin');
        $data['operator']=$massage;
        $this->product = M('DepartmentWarehouse');
        $data['root_group_id']=$group_id;
        $result=$this->product->add($data);
		// echo $this->product->getlastsql();
        if($result){
            alert(1,'添加成功');
        }else{
            alert(0,'添加失败');
        }
    }
	public function edit_warehouse($id){
		if($id=='' || !is_numeric($id)){
            alert(0,'操作有误');
        }
        $list=M('Warehouse')->find($id);
        if(!$list){
            alert(0,'操作有误');
        }else{
            $this->assign('list',$list);
            $this->display();
        }
	}
	public function editD_warehouse($id,$warehouse_name,$pwd,$pwd2){
		if($warehouse_name==''){
            alert(0,'仓库名称不能为空');
        }

        // if($email==''){
            // alert(0,'E-mail不能为空');
        // }
        // if($username==''){
            // alert(0,'用户名不能为空');
        // }
        // if(!email($email)){
            // alert(0,'邮箱地址错误');
        // }
        if(M("Warehouse")->where("name='".$warehouse_name."' and id<>'".$id."'")->count()>=1){
            alert(0,'仓库名称已经存在！');
        }
        // if(M("Warehouse")->where("email='".$email."' and id<>'".$id."'")->count()>=1){
            // alert(0,'电子邮箱已经存在！');
        // }
        $data['name']=$warehouse_name;
        if($pwd!=''){
            if($pwd2!=$pwd){
                alert(0,'两次密码不相同');
            }
            $data['salt']=rand(10000,99999);
            $data['password']=md5($pwd.$data['salt']);
        }
        $data['email']=$email;

        $data['operator']=session('admin');
        $result=M("Warehouse")->where(array('id'=>$id))->save($data);
		// echo M("Warehouse")->getlastsql();
        if($result!==false){
            alert(1,'修改成功');
        }else{
            alert(0,'修改失败，请重试');
        }
	}
    public function department_edit($id){
        if($id==''){
            echo "错误";
        }
		
		$root=M('RootWarehouse')->order("sort")->select();
		$this->product = M('DepartmentWarehouse');
		$this->data=$this->product->find($id);
        $root_id=$this->product->where(array('id'=>$id))->getField('root_group_id');
        $arr_root=explode(',',$root_id);
        $new_arr=array();
		foreach($root as $k=>$v){
			if(in_array($v['id'],$arr_root)){
				$v['checked']=1;
			}
            if($v['pid']==0){//顶级菜单
                foreach($root as $j=>$u){
					if(in_array($u['id'],$arr_root)){
						$u['checked']=1;
					}
					if($v['id']==$u['pid']){
						foreach($root as $js=>$us){
							if(in_array($us['id'],$arr_root)){
								$us['checked']=1;
							}
							if($u['id']==$us['pid']){
								foreach($root as $jss=>$uss){
									if(in_array($uss['id'],$arr_root)){
										$uss['checked']=1;
									}
									if($us['id']==$uss['pid']){
											$us['child'][]=$uss;
									}
								}
								$u['child'][]=$us;
							}
						}
						$v['child'][]=$u;
					}
				}
				$new_arr[]=$v;
            }
        }
        $this->assign('list',$new_arr);
        $this->display();
    }
    public function department_editD($id,$group_id){
        $this->p = M('RootWarehouse');
        if($group_id==''){
            alert(0,'权限不能为空');
        }
        //////权限检查，是否具备这些权限
        $arr_id=explode(',',$group_id);
		// dump($arr_id);
		// die;
        foreach($arr_id as $v){
            if(!is_numeric($v)){
                alert('操作有误');
            }
        }
        $where['id']=array('IN',$arr_id);
        $result=$this->p->where($where)->getField('name',true);
        if(count($result)!=count($arr_id)){
            alert('操作有误');
        }
        $massage=session('admin');
        $data['operator']=$massage;
        $this->product = M('DepartmentWarehouse');
        $data['root_group_id']=$group_id;
        $result=$this->product->where(array('id'=>$id))->save($data);
        if($result){
            alert(1,'修改成功');
        }else{
            alert(0,'修改失败');
        }
    }
    public function department_del($id){
        if($id==''){
            alert(0,'操作有误');
        }
        ///////$id=1@2@3
        $group_id=explode('@',$id);
        $id=implode(',',$group_id);
        $result=M('DepartmentWarehouse')->delete($id);
        if($result){
            alert(1,'成功删除了'.$result.'条数据，共'.count($group_id).'条');
        }else{
            alert(0,'删除失败');
        }
    }

	
}